专业的建站公司服务,花果园网站建设,网络搭建与维护,古镇 网站建设文章目录 一、简介二、实现原理三、修改缓存范围 一、简介
Integer缓存池是一种优化技术#xff0c;用于提高整数对象的重用和性能。在Java中#xff0c;对于整数值在 -128 到 127 之间的整数对象#xff0c;会被放入缓存池中#xff0c;以便重复使用。这是因为在这个范围… 文章目录 一、简介二、实现原理三、修改缓存范围 一、简介
Integer缓存池是一种优化技术用于提高整数对象的重用和性能。在Java中对于整数值在 -128 到 127 之间的整数对象会被放入缓存池中以便重复使用。这是因为在这个范围内的整数值被频繁使用因此重用这些对象可以节省内存和提高性能。当使用自动装箱机制创建整数对象时如果对象的值在缓存池范围内会直接返回缓存池中的对象而不是创建新的对象。这个特性可以通过调用Integer.valueOf(int)方法来实现。
根据通过设置JVM-XX:AutoBoxCacheMax可以来修改缓存的最大值最小值改不了
二、实现原理
底层实现的原理是int 在自动装箱的时候会调用IntegervalueOf进而用到了 IntegerCache。 public static Integer valueOf(String s) throws NumberFormatException {return Integer.valueOf(parseInt(s, 10));}没有太多复杂的步骤只需要判断给定的值是否在指定范围内如果是的话则从 IntegerCache 中获取已经预先初始化好的缓存值。
这些缓存值在静态块中被初始化。
/*** Cache to support the object identity semantics of autoboxing for values between* -128 and 127 (inclusive) as required by JLS.** The cache is initialized on first usage. The size of the cache* may be controlled by the {code -XX:AutoBoxCacheMaxsize} option.* During VM initialization, java.lang.Integer.IntegerCache.high property* may be set and saved in the private system properties in the* sun.misc.VM class.*/private static class IntegerCache {static final int low -128;static final int high;static final Integer cache[];static {// high value may be configured by propertyint h 127;String integerCacheHighPropValue sun.misc.VM.getSavedProperty(java.lang.Integer.IntegerCache.high);if (integerCacheHighPropValue ! null) {try {int i parseInt(integerCacheHighPropValue);i Math.max(i, 127);// Maximum array size is Integer.MAX_VALUEh Math.min(i, Integer.MAX_VALUE - (-low) -1);} catch( NumberFormatException nfe) {// If the property cannot be parsed into an int, ignore it.}}high h;cache new Integer[(high - low) 1];int j low;//创建要缓存的值for(int k 0; k cache.length; k)cache[k] new Integer(j);// range [-128, 127] must be interned (JLS7 5.1.7)assert IntegerCache.high 127;}private IntegerCache() {}}这里还有一个有趣的面试题即在 Integer 类中数值在 127 以内的两个 Integer 对象会被认为是相等的而超过 127 的数值则不相等。这是因为在 Java 中对于数值在 -128 到 127 之间的整型对象会使用 IntegerCache 中预先初始化的对象。因此当数值在该范围内时它们实际上是同一个对象因此相等性比较会返回 true。这种行为不仅适用于 Integer 类也适用于 Long 类。 public static Long valueOf(long l) {final int offset 128;if (l -128 l 127) { // will cachereturn LongCache.cache[(int)l offset];}return new Long(l);}对于小数类型的 Float 和 Double不会有像整数类型那样的缓存机制。因为小数类型的数值范围非常广泛无法事先预先缓存所有可能的数值。因此对于 Float 和 Double 类型的对象相等性比较会根据它们的实际数值来判断而不是基于对象的引用。所以即使两个 Float 或两个 Double 对象的数值相同它们也不会被认为是相等的。
三、修改缓存范围 通过注释可知缓存值可以修改 验证默认情况下 添加JVM参数 -XX:AutoBoxCacheMax500 再次执行 发现i1和i2相等返回true说明参数生效了。